package my.suveng.oauth2.service.transaction;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.caller.CallerUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.querydsl.core.QueryResults;
import com.querydsl.jpa.impl.JPAQueryFactory;
import my.suveng.model.common.interfaces.response.IMessage;
import my.suveng.model.common.response.Message;
import my.suveng.oauth2.model.dto.UserDeleteDto;
import my.suveng.oauth2.service.auth.impl.AuthServiceImpl;
import my.suveng.oauth2.service.db.mysql.dao.jpa.SysPermissionRoleRepository;
import my.suveng.oauth2.service.db.mysql.dao.jpa.SysUserGroupRepository;
import my.suveng.oauth2.service.db.mysql.dao.jpa.SysUserRepository;
import my.suveng.oauth2.service.db.mysql.dao.jpa.SysUserRoleRepository;
import my.suveng.oauth2.service.db.mysql.model.entity.*;
import my.suveng.util.log.PlusLogFactoryHutool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 事务处理类
 *
 * @author suwenguang
 **/
@Service
public class UserTransactionService {

    // hutool日志
    private static final Log log = LogFactory.setCurrentLogFactory(new PlusLogFactoryHutool())
            .getLog(CallerUtil.getCaller().getName());

    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    @Autowired
    private AuthServiceImpl authService;
    @Autowired
    private SysPermissionRoleRepository sysPermissionRoleRepository;
    @Autowired
    private SysUserRoleRepository sysUserRoleRepository;
    @Autowired
    private SysUserGroupRepository sysUserGroupRepository;
    @Autowired
    private SysUserRepository sysUserRepository;

    /**
     * 删除用户
     *
     * @author suwenguang
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public IMessage<Object> delete(UserDeleteDto userDeleteDto) {
        QSysUser qSysUser = QSysUser.sysUser;
        SysUser sysUser = jpaQueryFactory.selectFrom(qSysUser).where(qSysUser.id.eq(userDeleteDto.getId())).fetchOne();
        if (ObjectUtil.isEmpty(sysUser)) {
            log.info("用户不存在,id={}", userDeleteDto.getId());
            return Message.error("用户不存在");
        }
        // 物理删除
        QSysUserGroup qSysUserGroup = QSysUserGroup.sysUserGroup;
        QueryResults<SysUserGroup> sysUserGroupQueryResults = jpaQueryFactory.selectFrom(qSysUserGroup)
                .where(qSysUserGroup.userId.eq(userDeleteDto.getId())).fetchResults();

        // 删除user-group关系
        List<SysUserGroup> sysUserGroupList = sysUserGroupQueryResults.getResults();
        if (CollUtil.isNotEmpty(sysUserGroupList)) {
            sysUserGroupList.forEach(e -> {
                sysUserGroupRepository.deleteById(e.getId());
            });
        }

        // 删除user-role关系
        QSysUserRole qSysUserRole = QSysUserRole.sysUserRole;
        QueryResults<SysUserRole> sysUserRoleQueryResults = jpaQueryFactory.selectFrom(qSysUserRole)
                .where(qSysUserRole.userId.eq(userDeleteDto.getId())).fetchResults();
        List<SysUserRole> sysUserRoleList = sysUserRoleQueryResults.getResults();
        if (CollUtil.isNotEmpty(sysUserRoleList)) {
            sysUserRoleList.forEach(e -> {
                sysUserRoleRepository.deleteById(e.getId());
            });
        }

        // 删除记录
        sysUserRepository.deleteById(userDeleteDto.getId());

        // 使其登录token失效

        return Message.successWithData(null);
    }
}
